package com.wn.date20190820Socket;

import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;


import com.wn.date20190821.FxApp;

import javafx.application.Platform;

/**
 * 发送消息
 * 
 * @author song
 *
 */
public class SentMsg
{
	private  String hostName;
	private  int port;
	private FxApp main;
	public SentMsg(String hostName,int port,FxApp main)
	{
		this.port = port;
		this.hostName = hostName;
		this.main=main;

	}

	/**
	 * 发送消息
	 * 
	 * @param str
	 * @throws Exception
	 * @throws UnknownHostException
	 */
	public void send(String str) throws Exception
	{
		new Thread(()->{
			
			try (Socket socket = new Socket(hostName, port);
					OutputStream os = socket.getOutputStream();
					BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os));)
			{
				// 写入
				writer.write(str);
				writer.flush();
				// 关闭
				socket.shutdownOutput();
			}catch (Exception e) {
				Platform.runLater(()->	main.setMsg("对方不在线，连接失败"));
				main.setLoggerInfo("对方不在线，连接失败");
				e.printStackTrace();
			}
		}).start();
		

	}

	public int getPort()
	{
		return port;
	}

	public void setPort(int port)
	{
		this.port = port;
	}

	public String getHostName()
	{
		return hostName;
	}

	public void setHostName(String hostName)
	{
		this.hostName = hostName;
	}
}
